package org.cgs.web.server.management;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.*;

import org.apache.log4j.Logger;
import org.cgs.web.beans.Student;
import org.cgs.web.common.Constants;
import org.cgs.web.common.Utility;
import org.cgs.web.database.DatabaseConnector;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public final class GenerateStudentsReport extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(GenerateStudentsReport.class);

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		// Get student info from web page form
		String courseCode = (String) request.getSession().getAttribute("courseCode");

		try
		{
			Document document = new Document();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			PdfWriter.getInstance(document, baos);
			document.open();
			
			List<Student> students = Utility.getAllStudentsData(courseCode);
			
			for(Student s:students)
			{
				document.add(new Paragraph("Name: " + s.getName()));
				document.add(new Paragraph("Student Number: " + s.getStudentNumber()));
				document.add(new Paragraph("Email: " + s.getEmail()));
				document.add(new Paragraph("Phone: " + s.getPhone()));
				document.add(new Paragraph("Program and Year: " + s.getProgramAndYear()));
				document.add(new Paragraph("Recent Course: " + s.getRecentCourse()));
				document.add(new Paragraph("Interest in Course: " + s.getWhyInterested()));
				document.add(new Paragraph("Subject Likes/Dislikes: " + s.getLikeSubject()));
				document.add(new Paragraph("Transportation: " + s.getTransportation()));
				document.add(new Paragraph("Teaching Experience: " + s.getTeachingExperience()));
				document.add(new Paragraph("Teaching Attraction: " + s.getTeachingAttraction()));
				//
				document.add(Utility.buildTimeTable(s.getTimes(), "Student Busy Times:"));
				
				document.add(Chunk.NEWLINE);
				document.add(Chunk.NEWLINE);
				document.add(Chunk.NEWLINE);
			}
			
			document.close();
			
			response.setContentType("application/pdf");
			response.setContentLength(baos.size());
			response.setHeader("Expires", "0");
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");

			ServletOutputStream out = response.getOutputStream();
			baos.writeTo(out);
			out.flush();
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		catch (DocumentException e)
		{
			e.printStackTrace();
		}
	} // End method
} // End class
